package com.mw.job.ui.event;

import com.mw.job.ui.bean.ZkProperties;
import com.mw.job.ui.context.SpringContextUtil;
import com.mw.job.ui.zookeeper.CuratorClient;
import com.xiaoleilu.hutool.util.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * Created by mengdexuan on 2017/5/18 17:59.
 */
public class DealWithStartedEvent implements ApplicationListener<ContextRefreshedEvent> {

	private static Logger log = LoggerFactory.getLogger(DealWithStartedEvent.class);

	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		ApplicationContext appContext = contextRefreshedEvent.getApplicationContext();

		SpringContextUtil springContextUtil = appContext.getBean(SpringContextUtil.class);
		ServerProperties serverProperties = appContext.getBean(ServerProperties.class);
		springContextUtil.setApplicationContext(appContext);
		ZkProperties zkProperties = appContext.getBean(ZkProperties.class);

		CuratorClient.connect(zkProperties.getConnectString());

		String ip = NetUtil.getLocalhostStr();

		StringBuffer sb = new StringBuffer();
		sb.append("http://").append(ip).append(":").append(serverProperties.getPort()).append(serverProperties.getContextPath());

		log.info("项目启动完毕！");
		log.info("访问地址 --> "+sb.toString());

		hook();
	}

	public void hook(){
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run() {
				log.info("jvm 关闭，触发钩子函数……");
				CuratorClient.close();
			}
		});
	}
}
